package com.hm.manage.utils;

import com.hm.common.core.domain.entity.SysDept;
import com.hm.common.core.domain.entity.SysUser;
import com.hm.system.mapper.SysDeptMapper;
import com.hm.system.mapper.SysUserMapper;
import com.hm.system.service.ISysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.util.UriComponentsBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class SmsService {

    @Value("${sms.url}")
    private  String smsUrl;
    @Value("${sms.userid}")
    private  String userId;
    @Value("${sms.account}")
    private  String account;
    @Value("${sms.password}")
    private  String password;
    @Value("${sms.action}")
    private  String action;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    public SmsService(
            @Value("${sms.url}") String smsUrl,
            @Value("${sms.userid}") String userId,
            @Value("${sms.account}") String account,
            @Value("${sms.password}") String password,
            @Value("${sms.action}") String action) {
        this.smsUrl = smsUrl;
        this.userId = userId;
        this.account = account;
        this.password = password;
        this.action = action;
    }

    public SmsService(){
        this.smsUrl = smsUrl;
        this.userId = userId;
        this.account = account;
        this.password = password;
        this.action = action;
    }



    public String sendSms(String mobile, String content)  {
        // 构建请求URL并自动编码参数
        //String url = smsUrl+"?action="+action+"&userid="+userId+"&account="+account+"&password="+password+"&mobile="+mobile+"&content="+content;
        // 构建请求URL并自动编码参数
        String url = UriComponentsBuilder.fromHttpUrl(smsUrl)
                .queryParam("action", action)
                .queryParam("userid", userId)
                .queryParam("account", account)
                .queryParam("password", password)
                .queryParam("mobile", mobile)
                .queryParam("content", content)
                .queryParam("sendtime", "")
                .queryParam("extno", "")
                .build()
                .toUriString();


        log.info("------发送短信请求URL：{}", url);
        // 发送GET请求并获取响应
        String block = WebClient.create()
                .get()
                .uri(url)
                .retrieve()
                .bodyToMono(String.class)
                .block();
        return parseXMLString(block);

    }

    public  String parseXMLString(String xmlString) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(xmlString));
            Document doc = builder.parse(is);
            // 现在你可以使用doc对象来访问XML结构，例如：
            NodeList returnstatus = doc.getDocumentElement().getElementsByTagName("returnstatus");
            for (int i = 0; i < returnstatus.getLength(); i++) {
                System.out.println("returnstatus: " + returnstatus.item(i).getTextContent());
            }
            return returnstatus.item(0).getTextContent();
            //System.out.println("Root element :" + doc.getDocumentElement().getNodeName().getBytes("returnstatus")[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return xmlString;
    }

    /***
     * 给部门下的所有人发短信
     * @param deptName
     * @param content
     */
    public void sendtoUserByDeptName(String deptName, String content)  {
        log.info("---------------开始执行------SmsService.sendtoUserByDeptName-----------------------");
        // 先获取到部门下的所有人
        SysDept sysDept = new SysDept();
        sysDept.setDeptName(deptName);
        List<SysDept> sysDepts = sysDeptMapper.selectDeptList(sysDept);
        List<SysUser> sysUsers = new ArrayList<>();

        // 非空判断
        if (!sysDepts.isEmpty()) {
            for (SysDept sysDept1 : sysDepts) {
                // 获取部门下的所有人员的手机号码
                SysUser sysUser = new SysUser();
                sysUser.setDeptId(sysDept1.getDeptId());
                sysUsers = sysUserMapper.selectUserList(sysUser);
            }
        }
        log.info("-------------------当前部门下的人员数量是：{}",sysUsers.size());

        if (sysUsers.isEmpty()) {
            log.info("---------{}",deptName+"部门下没有获取到人员信息");
        } else {
            // 遍历人员发送短信
            // 开始遍历 逻辑：手机号码不为空，且不为管理员（userId!=1）
            for (SysUser sysUser : sysUsers) {
                if (sysUser.getUserId() == 1 || sysUser.getPhonenumber().isEmpty() || Objects.equals(sysUser.getDelFlag(), "2") || sysUser.getStatus().equals("1")) {
                    log.info("----------------{}---{}",sysUser.getUserName(),"不需要发短信：为管理员或手机号为空");
                } else {
                    log.info("----------------{}---{}",sysUser.getUserName(),"开始发短信");
                    String messageres=sendSms(sysUser.getPhonenumber(), content);
                    if (messageres.equals("Success")) {
                        log.info("---发送成功-------{}----{}---",sysUser.getUserName(),content);
                    }
                }
            }
        }
        log.info("---------------结束执行------SmsService.sendtoUserByDeptName-----------------------");
    }
}